<!-- +----------------------------------------------------------------------
| 麦沃德科技赋能开发者，助力中小企业发展 
+----------------------------------------------------------------------
| Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
+----------------------------------------------------------------------
| 沃德代驾系统并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
+----------------------------------------------------------------------
| Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
+----------------------------------------------------------------------
| 订单详情-司机替用户下单 开发者: 麦沃德科技-半夏
+---------------------------------------------------------------------- -->

<template>
	<page-meta :page-style="'overflow:' + (pageShow ? 'hidden' : 'visible')"></page-meta>
	<view class="container flex-column" :style="{'--theme-color': themeColor}">
		<view class="container-map flex-item" v-if="loadEnd">
			<map id="map" class="map-box" :latitude="orderInfo.from_lat" :longitude="orderInfo.from_lng" :scale="mapScale" :markers="markersList" :polyline="polyline" @callouttap="openPoint" @regionchange="regionchange">
				<cover-view slot="callout" class="map-callout" v-if="routesInfo && Object.keys(routesInfo).length">
					<cover-view class="callout-info" :marker-id="3">{{routesInfo.distance}} {{routesInfo.duration}}</cover-view>
					<cover-view class="callout-address" :marker-id="1">
						<cover-view class="address-name">{{orderInfo.from_address}}</cover-view>
						<cover-image class="address-icon" src="/static/right_round.png"></cover-image>
					</cover-view>
					<cover-view class="callout-address" :marker-id="2">
						<cover-view class="address-name">{{orderInfo.to_address}}</cover-view>
						<cover-image class="address-icon" src="/static/right_round.png"></cover-image>
					</cover-view>
				</cover-view>
			</map>
			<block v-if="!orderInfo.to_address">
				<view class="map-label-box flex align-items-center" @click="toSelectAddress(1)" v-if="orderInfo.from_address">
					<view class="box-text text-ellipsis-more">{{orderInfo.from_address}}</view>
					<image class="box-icon" src="/static/right_round.png" mode="aspectFit"></image>
				</view>
				<view class="map-label-point" v-else></view>
				<view class="map-label-line"></view>
			</block>
			<image class="map-location" src="/static/location.png" mode="aspectFit" @click="resetStartAddress()" v-if="!orderInfo.to_address"></image>
		</view>
		<view class="container-main" v-if="loadEnd">
			<view class="main-column">
				<view class="column-group flex align-items-center" :style="{'--input-color': '#242629'}" @click="toSelectAddress(1)">
					<view class="group-point"></view>
					<view class="group-input flex-item text-ellipsis">
						<text v-if="orderInfo.from_address">{{orderInfo.from_address}}</text>
						<text v-else>正在获取上车位置...</text>
					</view>
					<view class="group-btn flex align-items-center">
						<view class="text">修改出发地</view>
						<image class="icon" src="/static/right_round.png" mode="aspectFit"></image>
					</view>
				</view>
				<view class="column-group flex align-items-center" :style="{'--input-color': themeColor}" @click="toSelectAddress(2)">
					<view class="group-point"></view>
					<block v-if="orderInfo.to_address">
						<view class="group-input flex-item text-ellipsis">{{orderInfo.to_address}}</view>
						<view class="group-btn flex align-items-center">
							<view class="text">修改目的地</view>
							<view class="icon" :style="{'background-image': 'url('+ iconMore +')'}" v-if="iconMore"></view>
						</view>
					</block>
					<view class="group-input flex-item text-ellipsis" v-else>选择目的地</view>
				</view>
			</view>
			<view class="main-column">
				<view class="column-title">替TA下单</view>
				<view class="column-input">
					<input class="input" v-model="orderInfo.report_mobile" maxlength="11" type="number" placeholder="请输入手机号" placeholder-class="placeholder">
				</view>
			</view>
			<view class="main-column">
				<view class="column-title">备注信息</view>
				<view class="column-textarea">
					<textarea class="textarea" v-model="orderInfo.remarks" placeholder="请输入备注信息" placeholder-class="placeholder"></textarea>
				</view>
			</view>
			<!-- IOS安全区域 -->
			<view class="safe-padding"></view>
		</view>
		<!-- 底部区 -->
		<view class="container-footer" v-show="loadEnd">
			<view class="footer-btn flex align-items-center">
				<view class="btn-info flex-item">
					<view class="info-price">预估<text class="text">{{parseFloat(estimatedAmount || 0).toFixed(2)}}</text>元</view>
					<view class="info-tag flex align-items-center" @click="openAmountDetailsModal()">
						<view class="text">价格明细</view>
						<image class="icon" src="/static/driver/arrow_down.png" mode="aspectFit"></image>
					</view>
				</view>
				<view class="btn-box" @click="handlePayment()">立即下单</view>
			</view>
			<view class="footer-read flex flex-center" @click="isRead = !isRead">
				<view class="read-radio" :class="{active: isRead}">
					<image src="/static/tick.png" mode="aspectFit" v-if="isRead"></image>
				</view>
				<view class="read-label">请仔细阅读并同意<text class="text" @click.stop="toAgreement()">《代驾协议》</text></view>
			</view>
			<view class="safe-padding"></view>
		</view>
		<!-- 价格明细弹窗 -->
		<amount-details-modal ref="amountDetailsModal" @onChange="pageChange"></amount-details-modal>
		<!-- 支付二维码弹窗 -->
		<payment-code-modal ref="paymentCodeModal" show-type="2" @onChange="pageChange"></payment-code-modal>
	</view>
</template>

<script>
	import { mapState } from "vuex"
	import QQMapWX from '@/common/qqmap-wx-jssdk.min.js'
	import svgData from "@/common/svg.js"
	import amountDetailsModal from "@/pages/driver/component/modal/amount-details.vue"
	import paymentCodeModal from "@/pages/driver/component/modal/payment-code.vue"
	export default {
		components: {
			amountDetailsModal,
			paymentCodeModal,
		},
		data() {
			return {
				// 页面是否阻止滚动
				pageShow: false,
				// 加载完成
				loadEnd: false,
				// 地图缩放级别
				mapScale: 17,
				// 地图标记点
				markersList: [],
				// 轨迹点
				polyline: [{
					points: [],
					color: "", //线的颜色
					width: 8, //线的宽度
				}],
				// 当前地址
				currentLocation: {
					latitude: 39.904179,
					longitude: 116.40738,
				},
				// 路线信息
				routesInfo: {},
				// 订单数据
				orderInfo: {},
				// 预估价
				estimatedAmount: 0,
				// 价格明细
				amountDetails: [],
				// 是否已读
				isRead: true,
				// 是否重新定位
				isResetLocation: false,
			}
		},
		computed: {
			...mapState({
				themeColor: state => state.app.themeColor,
				tencentMapKey: state => state.app.tencentMapKey,
				currentCity: state => state.app.currentCity,
				iconShield: state => {
					return svgData.svgToUrl("shield", state.app.themeColor)
				},
				iconMore: state => {
					return svgData.svgToUrl("more", state.app.themeColor)
				},
			})
		},
		onLoad() {
			this.loadEnd = true
			this.currentLocation = this.currentCity
			this.getAuthSetting()
		},
		onShow() {
			let pages = getCurrentPages();
			if (pages[pages.length - 1].$vm.selectAddress) {
				let item = pages[pages.length - 1].$vm.selectAddress
				if (item.type == 2) {
					this.orderInfo.to_address = item.title
					this.orderInfo.to_lat = item.latitude
					this.orderInfo.to_lng = item.longitude
				} else {
					this.orderInfo.city = `${item.province}/${item.city}/${item.district}`
					this.orderInfo.from_address = item.title
					this.orderInfo.from_lat = item.latitude
					this.orderInfo.from_lng = item.longitude
				}
				this.markersList = []
				this.polyline = []
				if (this.orderInfo.from_address && this.orderInfo.to_address) this.getPlanRoute()
				delete pages[pages.length - 1].$vm.selectAddress;
			} else if (this.loadEnd) {
				if (this.isResetLocation) {
					this.currentLocation = this.currentCity
					this.isResetLocation = false
					this.getAuthSetting()
				}
			}
		},
		methods: {
			// 改变页面滚动状态
			pageChange(state) {
				this.pageShow = state
			},
			// 获取位置权限
			async getAuthSetting() {
				try {
					const permissionStatus = await this.$util.checkLocationPermission()
					if (permissionStatus == 1) {
						this.getLocation(1)
					} else {
						this.$util.setLocationPermission(permissionStatus, (result) => {
							// #ifdef MP-WEIXIN
							if (result) this.getLocation(1)
							else this.getLocation(2)
							// #endif
							// #ifdef APP
							if (result) this.isResetLocation = true
							else this.getLocation(2)
							// #endif
						})
					}
				} catch (error) {
					this.getLocation(2)
					uni.showToast({
						title: error.message,
						icon: 'none',
						duration: 2000,
					})
				}
			},
			// 获取位置信息
			getLocation(type) {
				if (!this.tencentMapKey) {
					setTimeout(() => {
						this.getLocation(type)
					}, 200);
					return
				}
				var qqmapsdk = new QQMapWX({
					key: this.tencentMapKey
				})
				var data = { get_poi: 1 }
				if (type == 2 || type == 3) {
					data.location = {
						latitude: this.currentLocation.latitude,
						longitude: this.currentLocation.longitude,
					}
				}
				qqmapsdk.reverseGeocoder({
					...data,
					success: (res) => {
						const result = res.result
						if (type == 1) {
							this.currentLocation = {
								latitude: result.location.lat,
								longitude: result.location.lng,
							}
						}
						this.orderInfo.city = `${result.ad_info.province}/${result.ad_info.city}/${result.ad_info.district}`
						this.orderInfo.from_address = result.address_reference.landmark_l2.title
						this.orderInfo.from_lat = result.location.lat
						this.orderInfo.from_lng = result.location.lng
						if (type != 3) {
							this.mapScale = null;
							setTimeout(() => {
								this.mapScale = 17;
							}, 200);
						}
					},
					fail: () => {
						uni.showToast({
							title: '位置获取失败',
							icon: 'none',
							duration: 2000,
						})
					},
				})
			},
			// 拖拽地图
			regionchange(obj) {
				if (this.orderInfo.to_address) return
				if (obj.causedBy == "gesture" || obj.causedBy == "drag" || obj.causedBy == "scale") {
					if (obj.type == "begin") {
						this.orderInfo.from_address = ""
						this.orderInfo.from_lat = ""
						this.orderInfo.from_lng = ""
						this.orderInfo = { ...this.orderInfo }
					} else if (obj.type == "end") {
						uni.createMapContext("map", this).getCenterLocation({
							type: 'gcj02',
							success: (res) => {
								this.currentLocation = {
									latitude: res.latitude,
									longitude: res.longitude,
								}
								this.getLocation(3)
							},
						})
					}
				}
			},
			// 获取路线详情
			getPlanRoute(fn) {
				this.$util.request("driver.order.estimatedAmount", {
					city: this.orderInfo.city,
					from_lat: this.orderInfo.from_lat,
					from_lng: this.orderInfo.from_lng,
					to_lat: this.orderInfo.to_lat,
					to_lng: this.orderInfo.to_lng,
				}).then(res => {
					if (fn) fn()
					if (res.code == 1) {
						this.estimatedAmount = res.data.estimated_amount
						this.amountDetails = res.data.estimated_amount_details
						this.routesInfo = {
							distance: this.$util.meterToKilometer(res.data.routes[0].distance),
							duration: this.$util.minuteToHour(res.data.routes[0].duration),
						}
						var coors = res.data.routes[0].polyline;
						for (var i = 2; i < coors.length; i++) {
							coors[i] = coors[i - 2] + coors[i] / 1000000
						}
						var pl = []
						for (var i = 0; i < coors.length; i += 2) {
							pl.push({ latitude: coors[i], longitude: coors[i + 1] })
						}
						if (pl.length == 1) pl.push(pl[0])
						this.polyline = [{
							points: pl,
							color: "#00C47A",
							arrowLine: true,
							width: 8,
						}]
						this.markersList = [{
								id: 3,
								latitude: pl[pl.length - 1].latitude,
								longitude: pl[pl.length - 1].longitude,
								iconPath: "/static/location_e.png",
								width: 20,
								height: 39,
								opacity: 0,
								customCallout: {
									anchorX: 0,
									anchorY: 60,
									display: "ALWAYS",
								},
							},
							{
								id: 1,
								latitude: pl[0].latitude,
								longitude: pl[0].longitude,
								iconPath: "/static/location_s.png",
								width: 20,
								height: 39,
								customCallout: {
									anchorX: 0,
									anchorY: -4,
									display: "ALWAYS",
								},
							},
							{
								id: 2,
								latitude: pl[pl.length - 1].latitude,
								longitude: pl[pl.length - 1].longitude,
								iconPath: "/static/location_e.png",
								width: 20,
								height: 39,
								customCallout: {
									anchorX: 0,
									anchorY: -4,
									display: "ALWAYS",
								},
							},
						]
						this._mapContext = uni.createMapContext('map', this);
						this._mapContext.includePoints({
							padding: [100, 100, 80, 100],
							points: pl,
						});
					} else {
						this.orderInfo.to_address = ""
						this.orderInfo.to_lat = ""
						this.orderInfo.to_lng = ""
						this.orderInfo = { ...this.orderInfo }
						uni.showModal({
							title: "系统提示",
							content: res.msg,
							confirmText: "我知道了",
							confirmColor: this.themeColor,
							showCancel: false,
						})
					}
				}).catch(error => {
					if (fn) fn()
					console.error('获取路线详情 ', error)
				})
			},
			// 开始地点重置为当前位置
			resetStartAddress() {
				if (this.orderInfo.to_address) return
				this.orderInfo.from_address = ""
				this.orderInfo.from_lat = ""
				this.orderInfo.from_lng = ""
				this.orderInfo = { ...this.orderInfo }
				this.getAuthSetting()
			},
			// 跳转地址选择
			toSelectAddress(type) {
				this.$util.toPage({
					mode: 1,
					path: "/pages/public/select/address?type=" + (type == 2 ? 3 : 1),
					isToken: true,
				})
			},
			// 点击标记点气泡
			openPoint(e) {
				if (e.detail.markerId == 3) return
				this.toSelectAddress(e.detail.markerId)
			},
			// 打开价格明细弹窗
			openAmountDetailsModal() {
				if (!this.orderInfo.from_address) {
					uni.showToast({
						icon: "none",
						title: "请选择出发地",
					})
					return
				}
				if (!this.orderInfo.to_address) {
					uni.showToast({
						icon: "none",
						title: "请选择目的地",
					})
					return
				}
				this.$refs.amountDetailsModal.open(this.amountDetails, this.orderInfo.city)
			},
			// 跳转协议
			toAgreement() {
				this.$util.toPage({
					mode: 1,
					path: "/pages/driver/mine/settings/agreement?type=1"
				})
			},
			// 提交订单
			handlePayment() {
				if (!this.orderInfo.from_address) {
					uni.showToast({
						icon: "none",
						title: "请选择出发地",
					})
					return
				}
				if (!this.orderInfo.to_address) {
					uni.showToast({
						icon: "none",
						title: "请选择目的地",
					})
					return
				}
				if (!this.orderInfo.report_mobile) {
					uni.showToast({
						icon: "none",
						title: "请输入手机号",
					})
					return
				}
				if (!this.isRead) {
					uni.showToast({
						icon: "none",
						title: "请阅读并同意代驾协议",
					})
					return
				}
				let data = JSON.parse(JSON.stringify(this.orderInfo))
				uni.showLoading({
					title: "加载中",
					mask: true
				})
				this.$util.request("driver.order.create", data).then(res => {
					uni.hideLoading()
					if (res.code == 1) {
						this.$refs.paymentCodeModal.open(res.data.id, res.data?.conf?.code_url)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2500,
						})
					}
				}).catch(error => {
					uni.hideLoading()
					console.error('提交订单 ', error)
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		padding-bottom: 0;
	}

	.container {
		min-height: 100vh;
		position: relative;

		.container-map {
			width: 100%;
			height: 100%;
			position: sticky;
			top: 0;
			min-height: 30vh;

			.map-box {
				width: 100%;
				height: 640rpx;

				.map-callout {
					width: 100vw;
					display: flex;
					justify-content: center;
					position: relative;
				}

				.callout-address {
					border-radius: 8rpx;
					background: #FFF;
					box-shadow: 0 4rpx 8rpx 0 rgba(0, 0, 0, 0.25);
					padding: 14rpx;
					display: flex;
					align-items: center;
					max-width: 160px;

					.address-name {
						color: #242629;
						font-size: 24rpx;
						font-weight: 600;
						line-height: 34rpx;
						white-space: pre-wrap;
					}

					.address-icon {
						width: 24rpx;
						height: 24rpx;
						min-width: 24rpx;
						margin-left: 8rpx;
					}
				}

				.callout-info {
					color: #FFF;
					text-align: center;
					font-size: 24rpx;
					font-weight: 600;
					line-height: 34rpx;
					border-radius: 16rpx;
					background: #353C57;
					padding: 4rpx 10rpx;
					position: absolute;
					top: 0;
					left: 0;
				}
			}

			.map-label-line {
				position: absolute;
				left: 50%;
				top: 50%;
				z-index: 1;
				transform: translate(-50%, -100%);
				width: 8rpx;
				height: 38rpx;
				background: var(--theme-color);
			}

			.map-label-box {
				position: absolute;
				left: 50%;
				bottom: 50%;
				z-index: 2;
				transform: translate(-50%, -36rpx);
				border-radius: 8rpx;
				background: #FFF;
				box-shadow: 0 4rpx 8rpx 0 rgba(0, 0, 0, 0.25);
				padding: 14rpx;
				max-width: 50vw;

				.box-text {
					color: #242629;
					text-align: center;
					font-size: 24rpx;
					font-weight: 600;
					line-height: 34rpx;
					flex: 1;
				}

				.box-icon {
					margin-left: 8rpx;
					width: 24rpx;
					height: 24rpx;
					min-width: 24rpx;
				}
			}

			.map-label-point {
				position: absolute;
				left: 50%;
				bottom: 50%;
				z-index: 2;
				transform: translate(-50%, -36rpx);
				width: 32rpx;
				height: 32rpx;
				border: 8rpx solid var(--theme-color);
				border-radius: 50%;
				background: #FFF;
			}

			.map-location {
				position: absolute;
				right: 32rpx;
				bottom: 64rpx;
				width: 64rpx;
				height: 64rpx;
			}
		}

		.container-main {
			position: relative;
			z-index: 9;
			margin-top: -32rpx;
			border-radius: 32rpx 32rpx 0 0;
			background: #F7F7F7;
			padding: 32rpx 32rpx 232rpx;

			.main-column {
				border-radius: 16rpx;
				background: #FFF;
				padding: 32rpx;
				margin-top: 32rpx;

				&:first-child {
					margin-top: 0;
				}

				.column-group {
					margin-top: 32rpx;
					border-radius: 16rpx;
					border: 4rpx solid var(--input-color);
					background: #FFF;
					padding: 24rpx 28rpx;

					.group-point {
						width: 16rpx;
						height: 16rpx;
						border-radius: 50%;
						background: var(--input-color);
					}

					.group-input {
						margin-left: 16rpx;
						color: var(--input-color);
						font-size: 28rpx;
						font-weight: 600;
						line-height: 40rpx;
					}

					.group-btn {
						margin-left: 16rpx;
						opacity: .6;

						.text {
							color: var(--input-color);
							font-size: 28rpx;
							font-weight: 600;
							line-height: 40rpx;
						}

						.icon {
							margin-left: 8rpx;
							width: 32rpx;
							height: 32rpx;
							background-size: 32rpx;
						}
					}
				}

				.column-title {
					color: #242629;
					font-size: 28rpx;
					font-weight: 600;
					line-height: 40rpx;
				}

				.column-input {
					margin-top: 32rpx;

					.input {
						width: 100%;
						color: #242629;
						font-size: 28rpx;
						line-height: 40rpx;
						border-radius: 16rpx;
						background: #F3F4F7;
						padding: 28rpx 32rpx;
					}

					.placeholder {
						color: #8D929C;
					}
				}

				.column-textarea {
					margin-top: 24rpx;

					.textarea {
						width: 100%;
						color: #242629;
						font-size: 28rpx;
						line-height: 40rpx;
						border-radius: 16rpx;
						background: #F3F4F7;
						padding: 24rpx;
						box-sizing: border-box;
					}

					.placeholder {
						color: #8D929C;
					}
				}
			}
		}

		.container-footer {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 99;
			background: #FFF;

			.footer-btn {
				padding: 16rpx 32rpx;

				.btn-info {
					.info-price {
						color: #DE2828;
						font-size: 24rpx;
						line-height: 56rpx;

						.text {
							font-weight: 600;
							font-size: 40rpx;
							line-height: 56rpx;
						}
					}

					.info-tag {
						margin-top: 6rpx;

						.text {
							color: #8D929C;
							font-size: 24rpx;
							line-height: 34rpx;
						}

						.icon {
							margin-left: 8rpx;
							width: 24rpx;
							height: 24rpx;
						}
					}
				}

				.btn-box {
					margin-left: 24rpx;
					color: #FFF;
					text-align: center;
					font-size: 28rpx;
					font-weight: 600;
					line-height: 40rpx;
					width: 312rpx;
					height: 96rpx;
					min-width: 312rpx;
					border-radius: 48rpx;
					background: var(--theme-color);
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}

			.footer-read {
				padding: 16rpx 32rpx;

				.read-radio {
					width: 40rpx;
					height: 40rpx;
					background: #E1E1E1;
					border-radius: 50%;
					overflow: hidden;

					&.active {
						background: var(--theme-color);
					}
				}

				.read-label {
					margin-left: 16rpx;
					color: #242629;
					font-size: 28rpx;
					font-weight: 600;
					line-height: 40rpx;

					.text {
						color: var(--theme-color);
					}
				}
			}
		}
	}
</style>